package user

import (
	"entry_task/backend/src/middle"
	"entry_task/backend/src/utils"
	"entry_task/backend/src/vo"
	api "entry_task/entry_api/service"
	"entry_task/entry_web/src/mrpc"
	"github.com/gin-gonic/gin"
	"net/http"
)

type LoginReq struct {
	Username string `form:"username" json:"username" binding:"required"`
	Password string `form:"password" json:"password" binding:"required"`
}

func Login(c *gin.Context) {
	userInfoClient := mrpc.GetInstance().GetUserInfoClient()
	var req LoginReq
	if c.BindJSON(&req) != nil {
		c.JSON(http.StatusOK, vo.FailParamError())
		return
	}
	loginResp, err := userInfoClient.Login(c, &api.LoginReq{Username: req.Username, Password: req.Password})
	utils.CheckErr(err)
	if loginResp.Token == "" {
		c.JSON(http.StatusOK, vo.Fail(301, "用户名或密码错误"))
		return
	}
	c.JSON(http.StatusOK, vo.Success(loginResp.Token))
}

func GetById(c *gin.Context) {
	currentUser := middle.GetCurrentUser(c)
	if currentUser == nil {
		c.JSON(http.StatusOK, vo.NotLogin())
		return
	}
	userInfoClient := mrpc.GetInstance().GetUserInfoClient()
	userInfo, err := userInfoClient.GetById(c, &api.UserInfoReq{Id: currentUser.Id})
	utils.CheckErr(err)
	c.JSON(http.StatusOK, vo.Success(userInfo))
}

type UpdateUserInfoReq struct {
	//Id                string `form:"Username" json:"Username" binding:"required"`
	//CreateTime        string `form:"createTime" json:"createTime" binding:"required"`
	//UpdateTime        string `form:"updateTime" json:"updateTime" binding:"required"`
	Username          string `form:"username" json:"username" binding:"required"`
	ProfilePictureUrl string `form:"profilePictureUrl" json:"profilePictureUrl"`
	Nickname          string `form:"nickname" json:"nickname" binding:"required"`
}

func UpdateUserInfo(c *gin.Context) {
	userInfoClient := mrpc.GetInstance().GetUserInfoClient()
	var req UpdateUserInfoReq
	if c.BindJSON(&req) != nil {
		c.JSON(http.StatusOK, vo.FailParamError())
		return
	}
	currentUser := middle.GetCurrentUser(c)
	if currentUser == nil {
		c.JSON(http.StatusOK, vo.NotLogin())
		return
	}
	_, err := userInfoClient.UpdateUserInfo(c,
		&api.UpdateUserInfoReq{Id: currentUser.Id, ProfilePictureUrl: req.ProfilePictureUrl, Nickname: req.Nickname})
	utils.CheckErr(err)
	c.JSON(http.StatusOK, vo.SuccessSimple())
}
